package com.multitool.service;

import com.multitool.dto.UserResponse;
import com.multitool.entity.User;
import com.multitool.repository.UserRepository;
import com.multitool.security.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private JwtUtil jwtUtil;

    public UserResponse getUserProfile(String token) {
        String username = jwtUtil.extractUsername(token.replace("Bearer ", ""));
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        return new UserResponse(
                user.getId(),
                user.getUsername(),
                user.getEmail(),
                user.getAvatar(),
                user.getCreatedAt(),
                user.getIsActive()
        );
    }

    public UserResponse updateUserProfile(String token, UserResponse userRequest) {
        String username = jwtUtil.extractUsername(token.replace("Bearer ", ""));
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        if (userRequest.getEmail() != null && !userRequest.getEmail().equals(user.getEmail())) {
            if (userRepository.existsByEmail(userRequest.getEmail())) {
                throw new RuntimeException("邮箱已存在");
            }
            user.setEmail(userRequest.getEmail());
        }

        if (userRequest.getAvatar() != null) {
            user.setAvatar(userRequest.getAvatar());
        }

        user.setUpdatedAt(java.time.LocalDateTime.now());
        User updatedUser = userRepository.save(user);

        return new UserResponse(
                updatedUser.getId(),
                updatedUser.getUsername(),
                updatedUser.getEmail(),
                updatedUser.getAvatar(),
                updatedUser.getCreatedAt(),
                updatedUser.getIsActive()
        );
    }
}

